class Solution {
       class Module {
        public Module(int profits, int capital) {
            this.profits = profits;
            this.capital = capital;
        }

        int profits;
        int capital;
    }

    static Comparator<Module> compare = new Comparator<Module>() {
        public int compare(Module o1, Module o2) {
            if (o1.profits != o2.profits)
                return o2.profits - o1.profits;
            else
                return o1.capital - o2.capital;
        }

    };

    static Comparator<Module> compareCaptial = new Comparator<Module>() {
        public int compare(Module o1, Module o2) {
            return o1.capital - o2.capital;
        }

    };

    public static class SortByCaptial implements Comparator<Module> {
        @Override
        public int compare(Module o1, Module o2) {
            return o1.capital-o2.capital;
        }
    }



    // 502
    public  int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int count = 1;
        Module[] profitsCaptial=new Module[profits.length];
        for(int i=0;i<profits.length;i++){
            profitsCaptial[i]=new Module(profits[i],capital[i]);
        }
        Arrays.sort(profitsCaptial,new SortByCaptial());
        Queue<Module> q = new PriorityQueue<>(compare);
        int i = 0;
        while (count <= k) {
            while ( i < profits.length && w >= profitsCaptial[i].capital) {
                q.offer(new Module(profitsCaptial[i].profits,profitsCaptial[i].capital));
                i++;
            }

            if (q.isEmpty()) return w;
            Module n = q.poll();
            w += n.profits;
            count++;
        }
        return w;
    }

}